package com.my.app.tools.core.service.ocr;

import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.util.Base64Util;
import com.google.common.collect.Lists;
import com.my.app.tools.pojo.em.client.OcrClientBaiDu;
import com.my.app.tools.pojo.em.client.OcrClientTencent;
import com.my.app.tools.pojo.vo.GlobalResponseEntity;
import com.my.app.tools.util.LogUtil;
import com.tencentcloudapi.ocr.v20181119.models.GeneralBasicOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.GeneralBasicOCRResponse;
import com.tencentcloudapi.ocr.v20181119.models.TextDetection;
import org.json.JSONArray;

import java.util.HashMap;
import java.util.List;

public class OcrTencentBasicService implements IOcrApiService {

    /**
     * ocr文字识别（通用基础）
     *
     * @param imgData
     * @return
     * @author guochaohui
     * @date 2020-04-03 16:30
     */
    @Override
    public GlobalResponseEntity<List<String>> imageOcr(byte[] imgData) {
        try {
            GeneralBasicOCRRequest req = new GeneralBasicOCRRequest();
            req.setImageBase64(Base64Util.encode(imgData));
            req.setLanguageType("auto");
            GeneralBasicOCRResponse response = OcrClientTencent.INSTANCE.getClient().GeneralBasicOCR(req);
            LogUtil.info("ocr tencent basic result: " + JSONObject.toJSONString(response));
            TextDetection[] textDetections = response.getTextDetections();
            List<String> results = Lists.newArrayList();
            for (TextDetection textDetection : textDetections) {
                results.add(textDetection.getDetectedText());
            }
            return GlobalResponseEntity.success("识别成功", results);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.error("ocr tencent basic error: " + e.getMessage());
            return GlobalResponseEntity.failure(e.getMessage());
        }
    }

}